package net.lunjin.controller;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SqlInjectIntercepter implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		if(request.getMethod().toUpperCase().equals("GET")){//只针对get请求
			Enumeration<String> names = request.getParameterNames();
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				String[] values = request.getParameterValues(name);
				for (int i = 0; i < values.length; i++) {
					if (values[i].toUpperCase().indexOf("SELECT")>0||values[i].toUpperCase().indexOf("DELETE")>0
						||values[i].toUpperCase().indexOf("UPDATE")>0 ||values[i].toUpperCase().indexOf("INSERT")>0
						||values[i].toUpperCase().indexOf("OR")>0 ||values[i].toUpperCase().indexOf("AND")>0
						||values[i].toUpperCase().indexOf("'")>0 ||values[i].toUpperCase().indexOf("=")>0) {
						response.setContentType("text/html;charset=utf-8");
						response.getWriter().print("请不要尝试注入,如果检测到你有多次注入的动作,我们会保留报警的权利,你的ip地址是:["+request.getRemoteAddr()+"],谢谢合作!<br><a href='#' onclick='history.go(-1)'>返回</a>");
						return false;
					}
				}
			}
		}
		return true;
	}
}
